package service;

import org.apache.commons.fileupload.FileItem;
import top.ConfigCenter;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class FileStoreServiceImp implements FileStoreService {

    private static FileStoreServiceImp fileServiceImp = new FileStoreServiceImp();
    public static FileStoreServiceImp getFileServiceImp() {
        return fileServiceImp;
    }

    private FileStoreServiceImp() {}

    /**
     * 存储一个用户上传的文件的实现
     * @param req 用户会话
     * @param file 文件文件
     * @param storePath 文件的存放路径，以/开头，表示服务器设定的文件存放根目录
     * @param filename 文件名
     * @return 文件的URI
     */
    @Override
    public String store(HttpServletRequest req, FileItem file, String storePath, String filename) {
        String fileHome = getFileHome(req) + storePath;

        filename = fileHome + '/' + filename;
        File newFile = new File(filename);

        System.out.println(filename);
        try {
            try {
                if(newFile.exists()) newFile.delete();
                if(!newFile.createNewFile()) return null;
            } catch (IOException e) {
                File homeDir = new File(fileHome);
                homeDir.mkdirs();
                if(newFile.exists()) newFile.delete();
                if(!newFile.createNewFile()) return null;
            }

            file.write(newFile);

            System.out.println("rel:" + newFile.getPath());
            System.out.println("abs:" + newFile.getAbsolutePath());
            return storePath + '/' + filename;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean remove(String pathname) {
        return false;
    }

    @Override
    public String move(String pathname, String newPathname) {
        return null;
    }

    @Override
    public boolean exists(String pathname) {
        return false;
    }

    @Override
    public String getFileHome(HttpServletRequest req) {
        return req.getServletContext().getRealPath(ConfigCenter.FILEHOME).replace('\\', '/');
    }
}
